import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.ui.Mouse;
import flash.utils.Dictionary;
import flash.utils.Timer;
import mx.charts.ChartItem;
import mx.charts.DateTimeAxis;
import mx.charts.HitData;
import mx.charts.chartClasses.DataDescription;
import mx.charts.events.ChartItemEvent;
import mx.charts.series.ColumnSeries;
import mx.charts.series.PieSeries;
import mx.charts.series.items.ColumnSeriesItem;
import mx.charts.series.items.PieSeriesItem;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.ComboBox;
import mx.effects.Effect;
import mx.events.ListEvent;
import mx.graphics.IFill;
import mx.graphics.SolidColor;
import mx.managers.PopUpManager;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
[Bindable]
private var acColumn:ArrayCollection;
[Bindable]
private var acRatio:ArrayCollection;
private var units:String;
private var uri:String;
[Bindable]
private var max:Number;

private function init():void
{
	acRatio = new ArrayCollection();
	acColumn = new ArrayCollection();
	electricid = Application.application.parameters.electricid;
	trace(electricid);
	if (electricid.length == 0)
	{
		Alert.show("尚未取得電號，請登入");
		return;
	}
	var loader:URLLoader = new URLLoader();
	loader.addEventListener(Event.COMPLETE, configLoad);
	loader.dataFormat = URLLoaderDataFormat.TEXT;
	loader.load(new URLRequest('config.xml'));
}
private var tickTime:Number;

private function configLoad(event:Event):void
{
	var loader:URLLoader = event.currentTarget as URLLoader;
	var xml:XML          = new XML(loader.data);
	uri = xml.Usage;
	tickTime = Number(xml.Time);
	createDict();
	createSelectorData();
	cbSelector.addEventListener(ListEvent.CHANGE, selectorChange);
	btnDay.addEventListener(MouseEvent.CLICK, switchRange);
	btnMonth.addEventListener(MouseEvent.CLICK, switchRange);
	btnYear.addEventListener(MouseEvent.CLICK, switchRange);
	btnLeft.addEventListener(MouseEvent.CLICK, scrollRange);
	btnRight.addEventListener(MouseEvent.CLICK, scrollRange);
}

private function createDict():void
{
	dict = new Dictionary();
	for each (var item:Object in acDiv)
	{
		dict[item.type] = item.name;
	}
}

private function newLoading():void
{
	loading = PopUpManager.createPopUp(this, loadingBox, true) as loadingBox;
	loading.x = (this.width - loading.width) / 2;
	loading.y = (this.height - loading.height) / 2;
}

private function delLoading():void
{
	if (loading != null)
	{
		PopUpManager.removePopUp(loading);
		loading = null;
	}
}

private function getResult(event:ResultEvent):void
{
	setColumnSeries(true);
	delLoading();
	var result:Object = event.result;
	if (!result.hasOwnProperty('data'))
	{
		Alert.show("取得資料錯誤，請稍候再試");
		return;
	}
	columnAxis.dataUnits = units;
	switch (columnAxis.dataUnits)
	{
		case "months":
		{
			columnAxis.dataInterval = 1;
			lblPrevious = "前一年使用量";
			lblCurrent = "當年使用量";
			break;
		}
		case "days":
		{
			columnAxis.dataInterval = 1;
			lblPrevious = "前一個月使用量";
			lblCurrent = "當月使用量";
			break;
		}
		case "hours":
		{
			columnAxis.dataInterval = 1;
			lblPrevious = "前一天使用量";
			lblCurrent = "當天使用量";
			break;
		}
	}
	var item:Object;
	var data:Object = event.result.data;
	item = data.change;
	setChange(item.previous_usage, item.current_usage, item.ratio);
	item = data.green;
	setGreen(item.total_co2, item.total_gasoline, item.total_tree);
	item = data.ratio;
	setColumn(item.bar as ArrayCollection);
	/** setRatio */
	item = data.home;
	if (item == '0')
	{
		acRatio.removeAll();
	}
	else
	{
		setRatio(item.Eqp as ArrayCollection)
	}
}

private function setRatio(source:ArrayCollection):void
{
	var item:Object;
	for each (item in source)
	{
		item.equip_usage = item.equip_usage;
		var other:Boolean = String(item.equip_ID).indexOf('-') > -1 ? false : true;
		if (other)
		{
			item.label = dict[String(item.equip_ID)];
		}
		else
		{
			var array:Array = String(item.equip_ID).split('-');
			item.label = dict[array[0]].toString() + '-' + array[1].toString();
		}
	}
	acRatio = source;
	acRatio.refresh();
}

private function setColumn(source:ArrayCollection):void
{
	max = 0;
	var item:Object;
	var start:Number = new Date().getTime();
	var end:Number   = 0;
	for each (item in source)
	{
		var temp:String = item.TimeStamp;
		temp = temp.replace(/-/g, "/");
		var num:Number = Date.parse(temp);
		if (num >= end)
		{
			end = num;
		}
		if (start >= num)
		{
			start = num;
		}
		item.TimeStamp = new Date(num);
		var total:Number = 0;
		item.Rate_A = Number(item.Rate_A);
		item.Rate_C = Number(item.Rate_C);
		item.Rate_D = Number(item.Rate_D);
		item.Rate_N = Math.max(item.Rate_A, item.Rate_C, item.Rate_D);
		if (item.Rate_N == item.Rate_A)
		{
			item.Fill = 'a';
		}
		if (item.Rate_N == item.Rate_C)
		{
			item.Fill = 'c';
		}
		if (item.Rate_N == item.Rate_D)
		{
			item.Fill = 'd';
		}
		total += item.Rate_A + item.Rate_C + item.Rate_D;
		if (total > max)
		{
			max = total;
		}
		item.Rate = total;
		if (units == 'hours')
		{
			item.Rate_A = 0;
			item.Rate_C = 0;
			item.Rate_D = 0;
		}
	}
	var s:Date = new Date(start);
	var e:Date = new Date(end);
	columnAxis.dataUnits = units;
	switch (columnAxis.dataUnits)
	{
		case "months":
		{
			strTimeRange = s.fullYear.toString();
			break;
		}
		case "days":
		{
			strTimeRange = getYearMonth(s);
			break;
		}
		case "hours":
		{
			strTimeRange = getDate(s);
			setColumnSeries(false);
			break;
		}
	}
	acColumn = source;
	acColumn.refresh();
}

private function setColumnSeries(bool:Boolean):void
{
	csA.visible = bool;
	csC.visible = bool;
	csD.visible = bool;
	csN.visible = !bool;
}

private function colorFunc(item:ChartItem, index:Number):IFill
{
	var data:Object   = item.item;
	var sc:SolidColor = new SolidColor(0);
	switch (data.Fill)
	{
		case 'a':
		{
			sc = scA;
			break;
		}
		case 'c':
		{
			sc = scC;
			break;
		}
		case 'd':
		{
			sc = scD;
			break;
		}
	}
	return sc;
}

private function setChange(old:Number, now:Number, ratio:Number):void
{
	fadeOut.play();
	usagePrevious = old;
	usageCurrent = now;
	usageVariation = ratio;
	if (usageVariation > 0)
	{
		lblVariation = "用電量上升";
	}
	else if (usageVariation < 0)
	{
		lblVariation = "用電量下降";
	}
	else
	{
		lblVariation = "用電量不變";
	}
	setTimeout(showVariation, 800);
}

private function setGreen(co2:Number, gas:Number, tree:Number):void
{
	strCO2 = co2.toFixed(digit);
	strTREE = tree.toFixed(digit);
	strGAS = gas.toFixed(digit);
}

private function showVariation():void
{
	if (usageVariation > 0)
	{
		imgCurrent.scaleY = 1;
		imgPrevious.scaleY = usagePrevious / usageCurrent;
		imgVariation.source = firstUp;
		variationUp.play();
	}
	else if (usageVariation < 0)
	{
		imgPrevious.scaleY = 1;
		imgCurrent.scaleY = usageCurrent / usagePrevious;
		imgVariation.source = firstDown;
		variationDown.play();
	}
}

private function createSelectorData():void
{
	acSelector = new ArrayCollection();
	var now:Date = new Date();
	for (var i:int; i < 12; i++)
	{
		var date:Date   = new Date(now.fullYear, now.month - i, 1);
		var item:Object = new Object();
		item.label = getYearMonthC(date);
		item.data = date;
		acSelector.addItem(item);
	}
	acSelector.refresh();
	var timer:Timer = new Timer(tickTime);
	timer.addEventListener(TimerEvent.TIMER, timerTick);
	//timer.start();
	//passionDay(new Date());
	selectorChange();
}

private function timerTick(e:TimerEvent):void
{
	if (loading == null)
	{
		lastFunc.call(null, lastDate);
	}
}

/** ComboBox 選取後所觸發的事件 */
private function selectorChange(event:ListEvent = null):void
{
	var item:Object = cbSelector.selectedItem;
	passionMonth(item.data as Date);
}
private var lastFunc:Function;
private var lastDate:Date;

private function passionYear(start:Date):void
{
	var now:Date = new Date();
	if (start.getTime() > now.getTime())
	{
		alertStartError();
		return;
	}
	units = "months";
	lastFunc = passionYear;
	getData(start, "years");
}

private function passionMonth(start:Date):void
{
	var now:Date = new Date();
	if (start.getTime() > now.getTime())
	{
		alertStartError();
		return;
	}
	units = "days";
	lastFunc = passionMonth;
	getData(start, "months");
}

private function passionDay(start:Date):void
{
	var now:Date = new Date();
	if (start.getTime() > now.getTime())
	{
		alertStartError();
		return;
	}
	units = "hours";
	lastFunc = passionDay;
	getData(start, "days");
}

private function columnClick(event:ChartItemEvent):void
{
	return;
	var item:Object = event.hitData.item;
	var date:Date   = item.TimeStamp as Date;
	var start:Date;
	switch (columnAxis.dataUnits)
	{
		case "months":
		{
			/** 年資料，圖表時間單位為月，點擊後呈現該月的日資料 */
			start = new Date(date.fullYear, date.month, 1);
			passionMonth(start);
			break;
		}
		case "days":
		{
			/** 月資料，圖表時間單位為日，點擊後呈現該日的小時資料 */
			start = new Date(date.fullYear, date.month, date.date);
			passionDay(start);
			break;
		}
		case "hours":
		{
			return;
			break;
		}
	}
	acColumn.removeAll();
}

private function getData(start:Date, unit:String):void
{
	lastDate = start;
	var service:HTTPService = new HTTPService();
	service.showBusyCursor = true;
	var s:String       = getFullDate(start);
	var siteUrl:String = uri;
	siteUrl += "?starttime=" + s;
	siteUrl += "&electricid=" + electricid;
	siteUrl += "&interval=" + unit.substr(0, unit.length - 1);
	siteUrl += "&timestamp=" + new Date().getTime();
	service.url = siteUrl;
	trace(service.url);
	switch (unit)
	{
		case "years":
		case "months":
		{
			columnChart.type = "stacked";
			break;
		}
		case "days":
		{
			columnChart.type = "clusterrd";
			break;
		}
	}
	sDate = start;
	service.addEventListener(ResultEvent.RESULT, getResult);
	newLoading();
	service.send();
}

private function columnDataTipFunction(e:HitData):String
{
	var result:String;
	var series:ColumnSeries    = e.element as ColumnSeries;
	var sitem:ColumnSeriesItem = e.chartItem as ColumnSeriesItem;
	var item:Object            = e.item;
	var yField:Number          = Number(e.item[series.yField]);
	if (isNaN(yField) || yField == 0)
	{
		return '';
	}
	var yValue:Number = Number(item.Rate);
	var ratio:Number  = (yField / yValue) * 100;
	switch (columnChart.type)
	{
		case "stacked":
		{
			result = "類別：" + series.displayName;
			result += "\n" + "時間：" + getDate(item.TimeStamp);
			result += "\n" + "數值：" + yField.toFixed(digit) + " kWh" + "　(" + ratio.toFixed(digit) + "%)";
			result += "\n" + "總值：" + yValue.toFixed(digit) + " kWh";
			break;
		}
		case "clusterrd":
		{
			result = "類別：";
			if (item.Fill == 'a')
			{
				result += '尖峰';
			}
			else if (item.Fill == 'c')
			{
				result += '離峰';
			}
			else if (item.Fill == 'd')
			{
				result += '周末半尖峰';
			}
			result += "\n" + "時間：" + getTime(item.TimeStamp);
			result += "\n" + "數值：" + yField.toFixed(digit) + " kWh";
			break;
		}
	}
	return result;
}

private function pieDataTipFunction(e:HitData):String
{
	var result:String       = '';
	var series:PieSeries    = e.element as PieSeries;
	var sitem:PieSeriesItem = e.chartItem as PieSeriesItem;
	var item:Object         = e.item;
	var ratio:Number        = Number(item.equip_usage);
	result = "電器：" + item.label;
	result += "\n" + "電量：" + ratio.toFixed(2) + " kWh";
	result += "\n" + "比例：" + sitem.percentValue.toFixed(digit) + " %";
	return result;
}

private function switchRange(event:MouseEvent):void
{
	var style:String = (event.currentTarget as Button).styleName.toString();
	style = style.replace('btn', '');
	var start:Date;
	switch (style)
	{
		case 'Day':
		{
			if (columnAxis.dataUnits == 'months')
			{
				/** 在年資料的情況下，按下天 */
				start = new Date(sDate.fullYear, 0, 1);
				passionDay(start);
			}
			else if (columnAxis.dataUnits == 'days')
			{
				/** 在月資料的情況下，按下天 */
				start = new Date(sDate.fullYear, sDate.month, 1);
				passionDay(start);
			}
			break;
		}
		case 'Month':
		{
			if (columnAxis.dataUnits == 'months')
			{
				/** 在年資料的情況下，按下月 */
				start = new Date(sDate.fullYear, 0, 1);
				passionMonth(start);
			}
			else if (columnAxis.dataUnits == 'hours')
			{
				/** 在天資料的情況下，按下月 */
				start = new Date(sDate.fullYear, sDate.month, 1);
				passionMonth(start);
			}
			break;
		}
		case 'Year':
		{
			if (columnAxis.dataUnits == 'days')
			{
				/** 在月資料的情況下，按下年
				 *  該顯示當年度一整年的資料 */
				start = new Date(sDate.fullYear, 0, 1);
				passionYear(start);
			}
			else if (columnAxis.dataUnits == 'hours')
			{
				/** 在天資料的情況下，按下年。
				 *  該顯示當年初至當天的資料 */
				start = new Date(sDate.fullYear, 0, 1);
				passionYear(start);
			}
			break;
		}
	}
}

private function scrollRange(event:MouseEvent):void
{
	var style:String = (event.currentTarget as Button).styleName.toString();
	style = style.replace('btn', '');
	var start:Date;
	var now:Date = new Date();
	switch (columnAxis.dataUnits)
	{
		case "months":
		{
			if (style == "Left")
			{
				start = new Date(sDate.fullYear - 1, 0, 1);
			}
			else if (style == "Right")
			{
				start = new Date(sDate.fullYear + 1, 0, 1);
			}
			passionYear(start);
			break;
		}
		case "days":
		{
			if (style == "Left")
			{
				start = new Date(sDate.fullYear, sDate.month - 1, 1);
			}
			else if (style == "Right")
			{
				start = new Date(sDate.fullYear, sDate.month + 1, 1);
			}
			passionMonth(start);
			break;
		}
		case "hours":
		{
			if (style == "Left")
			{
				start = addDays(sDate, -1);
			}
			else if (style == "Right")
			{
				start = addDays(sDate, 1);
			}
			passionDay(start);
			break;
		}
	}
}

private function alertStartError():void
{
	Alert.show(startError);
}

private function dateLabelFunction(value:Date, lastValue:Date, asix:DateTimeAxis):String
{
	var result:String;
	switch (columnAxis.dataUnits)
	{
		case "months":
		{
			result = getYearMonth(value);
			break;
		}
		case "days":
		{
			result = getMonthDay(value);
			break;
		}
		case "hours":
		{
			result = getHourMinute(value);
			break;
		}
	}
	return result;
}
